

import { Input, message, Modal } from 'antd'
import { LoadingOutlined } from '@ant-design/icons'
import { subscribe, unsubscribe } from 'pubsub-js';
import { useEffect, useState } from 'react';
import { connect } from 'react-redux';
import { getJoinGroup } from '../../assets/js/api';
import { joinGroup } from '../../event-type';

import { tip, tip_txt } from './index.module.css'

function GroupJoin(props) {

    const {user} = props;

    const [joinModalVisibel, setJoinModalVisibel] = useState(false);
    const [joinGroupID, setJoinGroupID] = useState(0);
    const [remarks, setRemarks] = useState('');
    const [loading, setLoading] = useState(false);
    const [retry, setRetry] = useState(false);


    useEffect(() => {
        subscribe(joinGroup, (event, group_id) => {
            setJoinModalVisibel(true);
            setJoinGroupID(group_id);
        });
        return () => {
            unsubscribe(joinGroup);
        }
    }, []);
    useEffect(() => {
        // 退出将输入清空
        if (!joinModalVisibel) {
            setRetry(false);
            setRemarks('');
            setLoading(false);
        }
    }, [joinModalVisibel]);

    function sendJoinMessage() {
        // 发送加入群组信息
        setLoading(true);

        getJoinGroup({user_id: user.id, group_id: joinGroupID, message: remarks})
        .then(res => {
            const {code, message:content} = res.data;
            if (code === 1) {
                message.success({content});
                setJoinModalVisibel(false);
                setRetry(false);
                return;
            }
            setRetry(true);
        })
        .catch(err => {
            console.log(err.code);

            message.error({content: '网络错误'});
            setRetry(true);
            setRemarks('');
        })
        .finally(() => {
            setLoading(false);
        });
    }

    return (
        <Modal
            visible={joinModalVisibel}
            centered={true}
            title="添加群"
            maskClosable={false}
            zIndex={1001}
            onCancel={() => setJoinModalVisibel(false)}
            onOk={sendJoinMessage}
        >
            <div>添加备注信息</div>
            <Input value={remarks} onChange={val => setRemarks(val.target.value)} />
            <div className={tip}>
                {
                    loading ?
                        <LoadingOutlined /> :
                        retry ? 
                            <span className={tip_txt}>网络错误, 请稍后再试</span> : ''
                }
            </div>
        </Modal>
    )   
}


function mapStateToProps(state) {
    return {
        user: state.user
    }
}
export default connect(
    mapStateToProps,
    {

    }
)(GroupJoin);

